<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Page extends BIT_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function __construct()
	{
		parent::__construct();

		$this->header_views = array('common/header');
		$this->footer_views = array('common/footer');

		$this->load_standards();
	}

	public function tack_for_bestallning(){
		$this->v('pages/tack');
	}

	public function index()
	{
		$this->view_data["product_html"] = $this->getProductBoxHtml( $this->produkter->getStartpageProducts( 6 ) );
		$this->view_data['news'] = $this->news->getLatestNews(4);

		$this->view_data['widgets'] = array( 
			$this->load->view('widgets/newsletter', null, TRUE) 
		);

		$this->v('pages/home');
	}
	
	public function sortiment(){
		$this->view_data["product_html"] = $this->getProductBoxHtml( $this->produkter->getProductPageProducts() );
		$this->v('pages/sortiment');
	}

	public function recept( $page = 1 ){
		$pagesize = 10;
		$this->view_data['recipes'] = $this->recept->getRecipeList($pagesize, $page);
		$this->view_data['pages'] = ceil($this->recept->count() / $pagesize);

		$this->v('pages/recept');
	}

	public function view_recept( $slug ){

		$recipe = $this->recept->getRecipe( $slug );
		$prods_in_rec = $this->getProductBoxHtml( $this->recept->getProductsInRecipe( $recipe->id ));
		
		$this->view_data['widgets'] = array( 
			$this->load->view('widgets/products_in_recipe', array('products_html' => $prods_in_rec), TRUE) 
		);

		$this->view_data['recept'] = $recipe;
		$this->v('pages/view_recept');
	}

	public function about(){
		$this->view_data['widgets'] = array(
			0 => $this->load->view('widgets/workwithus.php', null, TRUE),
			1 => $this->load->view('widgets/newsletter.php', null, TRUE)
		);

		// Show page
		$this->v('pages/about');
	}

	public function news( $id ){

		// Parse to int
		$id = intval($id);

		// Get current article
		$article = $this->db->get_where('news', array('id' => $id))->result();
		$this->view_data['article'] = $article[0];

		// Get the rest of'm
		$list = $this->db->order_by('datum','DESC')->get('news')->result();
		$this->view_data['widgets'] = array(
			$this->load->view('widgets/newslist.php', array(
				"articles" => $list,
				"title" => "Arkiv"
			), TRUE)
		);

		// Show page
		$this->v('pages/article');
	}
	public function product( $id ){

		// Get bestselling widget and data
		$widget_data = array('bestsellers_html' => $this->getProductBoxHtml( $this->produkter->getBestSellers() ));
		$this->view_data['widgets'] = array($this->load->view('widgets/bestsellers', $widget_data, TRUE));

		// Get product info
		$id = intval( $id );
		// Recalculate price to price / package instead of price / kg
		$packageprice = true;
		$product = $this->produkter->getProduct( $id, $packageprice );
		$this->view_data['product'] = $product;

		// Get 2 most popular recipes
		$this->view_data['relatedRecipes'] = $this->recept->getProductRelatedRecipes( $product->typ, 2 );

		// Display page
		$this->v('pages/produkt');
	}

	public function contact(){
		$mail_sent = false;

		# Loading configuration file mail_config.php
		$this->config->load('mail_config',true);

        if ($this->input->post('q'))
        {
        	$this->load->helper(array('form', 'url'));
			$this->load->library('form_validation');
			$form_rules = array(
				array(
					'field' => 'from',
					'label' => 'epost',
					'rules' => 'trim|valid_email|required'
				),
				array(
					'field' => 'name',
					'label' => 'namn',
					'rules' => 'min_length[3]|required'
				),
				array(
					'field' => 'subject',
					'label' => 'ämne',
					'rules' => 'min_length[3]|required'
				),
				array(
					'field' => 'message',
					'label' => 'meddelande',
					'rules' => 'min_length[20]|required'
				)
			);
			$this->form_validation->set_message('required', 'Du måste fylla i %sfältet');
			$this->form_validation->set_message('min_length', '%s får inte vara kortare än %s tecken');
			$this->form_validation->set_message('valid_email', 'Epostadressen är ogiltig');

			$this->form_validation->set_rules($form_rules);
			
			if($this->form_validation->run() == TRUE)
			{
	            # Loading email library of Codeigniter
	            $this->load->library('email');
	            # Setting email address and name of the person sending the email
	            $this->email->from($this->input->post('from'),$this->input->post('name'));
	            # Setting email address of the recipient
	            $this->email->to($this->config->item('to','mail_config'));
	            # Setting email subject
	            $this->email->subject($this->input->post('subject'));
	            # Setting email message body
	            $this->email->message($this->input->post('message',true));
	            # If mail sending successful
	            if ($this->email->send())
	            {
	                # If $mail_sent = true; it will show a success message.
	                $mail_sent = true;
	            }
	        }
        }
        # Get contact form html
        # $this->view_data['html'] = $this->pages->getPageBySlug('kontakt');

        # Showing Contact Form
        $this->view_data['mail_sent'] = $mail_sent;
        $this->view_data['mailaddress'] = $this->config->item('to','mail_config');
        $this->v('pages/kontakt');
	}

	public function newsletter_signup(){

		if ($this->input->post('sign_up_email'))
        {
        	$this->load->helper(array('form', 'url'));
			$this->load->library('form_validation');
			$form_rules = array(
				array(
					'field' => 'sign_up_email',
					'label' => 'epost',
					'rules' => 'trim|valid_email|required'
				)
			);
			$this->form_validation->set_message('required', 'Du måste fylla i %sfältet');
			$this->form_validation->set_message('valid_email', 'Epostadressen är ogiltig');

			$this->form_validation->set_rules($form_rules);
			
			$added = false;
			$message = false;

			if($this->form_validation->run() == TRUE)
			{
				$email = $this->input->post('sign_up_email');
				
				# If not previously added, add now!
				if( $this->db->where('mail',$email)->count_all_results('mail_adresser') === 0 ) {
					# Update database with email address
					$added = $this->db->insert('mail_adresser', array('mail' => $email));
				}
				else {
					$message = "Epostadressen finns redan i vårt system. Får du inga mail? <a href='/kontakt'>Kontakta oss</a>";		
				}
	        }
	        else {
	        	$message = "Epostadressen du angav är ogiltig, vänligen kontrollera den och försök igen";
	        }
        }

        # Showing Contact Form
        $this->view_data['added'] = $added;
        $this->view_data['message'] = $message;
        $this->view_data['mailaddress'] = $this->config->item('to','mail_config');
        $this->v('pages/newsletter_signup');
	}

	public function getProductBoxHtml( $product ) {

		$template = 'common/product';
		
		// list of products?
		if(is_array($product)) {
			$html = "";
			foreach($product as $p){
				$html .= $this->load->view($template, array('product'=>$p), TRUE);
			}
			return $html;
		}
		// Single product?
		else {
			return $this->load->view( $template, array('product'=>array($product)), TRUE);
		}
	}

	public function create_unique_slug($table)
	{
	    $itms = $this->db->get($table)->result();

	    foreach( $itms as $item ) {
	    	$slug = $this->doslug( $item->namn );
	        $params ['slug'] = $slug;
	        //$this->db->where('id',$item->id);
	        //$this->db->update($table, $params);
		}
	}

	private function doslug( $url ){
	    $a = array('å', 'ä', 'ö', 'Å', 'Ä', 'Ö', '.');  
	    $b =array('a', 'a', 'o', 'A', 'A', 'O', '-');  
	    $slug = str_replace($a, $b, $url);  
	    $slug = strtolower($slug);  
	    $slug = preg_replace("/[^a-z0-9\s-]/", "", $slug);  
	    $slug = trim(preg_replace("/\s+/", " ", $slug));  
	    $slug = trim(substr($slug, 0, 45));  
	    $slug = preg_replace("/\s/", "-", $slug);  
	    return $slug;  
	}

	public function fix_slugs() {
		$this->create_unique_slug('produkter');
		$this->create_unique_slug('recept');
	}

	private function load_standards(){

		$sliderdata = array('products' => $this->produkter->getSliderProducts());	
		$this->view_data['slider_html'] = $this->load->view('pages/slider', $sliderdata, TRUE);
		$this->view_data['widgets'] = array();

		$this->load->library("cart_handler");
		$cart_data = array(
			'summary'	=> $this->cart_handler->get_count(),
			'price'		=> $this->cart_handler->get_total(),
			'display_css' => $this->cart_handler->get_count() > 0 ? "show" : "hide"
		);
		$this->view_data['cart_html'] = $this->load->view('widgets/cart', $cart_data, TRUE);
	}

}